package orm;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
public class SqlCreate {
	public static String  createInsertSql(String  tableName,HashMap<String,Object>  value ) {
		String[] sqlKeys = createSqlKeys(value);
		String sql_head="insert   into   "+tableName+"(";
		String sql_tail="values (";
	  for(int i=0;i<sqlKeys.length;i++){	
			String key=sqlKeys[i];
		 sql_head=sql_head+key+",";
		 sql_tail=sql_tail+"?,";
		}
		sql_tail=sql_tail.subSequence(0, sql_tail.length()-1).toString()+")";
		sql_head=sql_head.subSequence(0, sql_head.length()-1).toString()+")";
		  String sql=sql_head+sql_tail;
			System.out.println("insert sql:"+sql);
		 System.out.println( Arrays.asList(sqlKeys));	
		  return  sql;
	}
	
	public  static String[] createSqlKeys(String whereCause,HashMap<String,Object>  value){
		 int length=value.keySet().size();
		 HashMap<String, Object>  temp=new HashMap<String, Object>();
		  Iterator<String> iterator=value.keySet().iterator();
		  while(iterator.hasNext()){
			  String key=iterator.next();
			  temp.put(key, value.get(key));
		  }
		temp.remove(whereCause);		
		Iterator<String> keys=temp.keySet().iterator();
	  String[] sqlKeys=new String[length];
	  int i=0;
	  while(keys.hasNext()){	
		  sqlKeys[i]=keys.next();
		  i++;
	  }
	  sqlKeys[length-1]=whereCause;
		return sqlKeys;	
	}
	public  static String[] createSqlKeys(HashMap<String,Object>  value){
		 int length=value.keySet().size();
		 HashMap<String, Object>  temp=new HashMap<String, Object>();
		  Iterator<String> iterator=value.keySet().iterator();
		  while(iterator.hasNext()){
			  String key=iterator.next();
			  temp.put(key, value.get(key));
		  }	
		Iterator<String> keys=temp.keySet().iterator();
	  String[] sqlKeys=new String[length];
	  int i=0;
	  while(keys.hasNext()){	
		  sqlKeys[i]=keys.next();
		  i++;
	  }
		return sqlKeys;	
	}
	  public static void main(String[] args) {
		HashMap<String, Object> value=new HashMap<String, Object>();
		value.put("user_name", value);
		value.put("head_URL",value);
		value.put("uid",1);
		value.put("photo_URL",1);
		String[] sqlKeys = createSqlKeys(value);
		String sql = createInsertSql("user_db", value);
	        System.out.println( sql);	
	        System.out.println( Arrays.asList(sqlKeys));	
	}
	  public static String createUpdateSql(String tableName,String whereCause,HashMap<String,Object>  value){  
		  String sql_head="update "+tableName+" set ";
			String sql_tail=" where " +whereCause+" =?";
			String[] sqlKeys = createSqlKeys(whereCause,value);
			for(int i=0;i<sqlKeys.length-1;i++)			
			{
			 sql_head=sql_head+sqlKeys[i]+"=?,	";
			}
			sql_head=sql_head.subSequence(0, sql_head.length()-2).toString()+"";
			  String sql=sql_head+sql_tail;
			  return  sql;
	  }
}
